jQueryAPI.Update = {};

jQueryAPI.Update.InvokeApplicationUpdate = function ( options ) {
	if (DebugMode) air.trace('Starting Update Function');
	function defaults() {
		return {
			'updateXML':''
		};
	};
	options = jQuery.extend(defaults(), options);
	var request = new air.URLRequest(options.updateXML); 
	var loader = new air.URLLoader(); 
	
	loader.addEventListener(air.Event.COMPLETE, jQueryAPI.Update.AppVersionCheck);
	loader.load(request);
	
};

jQueryAPI.Update.AppVersionCheck = function ( event ) {
	
	var remoteVersionString = jQuery(event.target.data).find('version').text();
	var remoteVersion = remoteVersionString.split('.').reverse();
	
	var remoteAir = jQuery(event.target.data).find('url').text();
	var request = new air.URLRequest('app:/application.xml'); 
	var loader = new air.URLLoader(); 
	
	loader.addEventListener(air.Event.COMPLETE, checkVersions);
	loader.load(request);
	
	function checkVersions( event ) {
		var thisVersion = jQuery(event.target.data).find('version').text().split('.').reverse();
		
		var update = false;
	
		jQuery.each(thisVersion, function(i, item){
			if (item > remoteVersion[i]);
				update = true;
		});
			
		if (update) {
			if (DebugMode) air.trace('Update Found, starting download');
			var stream = new air.URLStream();
			stream.addEventListener(air.ProgressEvent.PROGRESS, updatingStatus);
			stream.addEventListener(air.Event.COMPLETE, updateApplication);
			stream.load( new air.URLRequest(remoteAir));
		}
		
		// Handlers
		function updatingStatus( event ) {
			var percentage = Math.round((event.bytesLoaded / event.bytesTotal) * 100);
			if (DebugMode) air.trace(percentage);
		}
		
		function updateApplication ( event ) {
			var filename = "jQueryAPI-" + remoteVersionString + ".air";
			var ba = new air.ByteArray();
			stream.readBytes(ba, 0, stream.bytesAvailable);
			updateFile = air.File.applicationStorageDirectory.resolvePath(filename);
			fileStream = new air.FileStream();
			fileStream.addEventListener( air.Event.CLOSE, installUpdate );
			fileStream.openAsync(updateFile, air.FileMode.WRITE);
			fileStream.writeBytes(ba, 0, ba.length);
	 		fileStream.close();
			
			function installUpdate ( event ) {
				if (DebugMode) air.trace('Invoking Update');
				var updater = new air.Updater();
				// Notice that the version name has to be present as a second parameter
				updater.update(updateFile, remoteVersionString);
			};
		};
	}
};
